<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>

<!--
 组件prop名称如果使用驼峰命名如：switchStyle,那么要求在模板中使用中画线进行分司写为：switch-style
-->
<div id="app">
  <my-switch @switch-change="change1" switch-style="mini" background-color="#f5f5f5" color="#333333"></my-switch>
  <div>开关状态：{{state1}}</div>
  <br>
  <my-switch @switch-change="change2" switch-style="normal" background-color="#f5f5f5" color="#333333"></my-switch>
  <div>开关状态：{{state2}}</div>
</div>

<script>
  const {createApp,ref,computed} = Vue

  const switchComponent = {
    // 定义外部属性
    props:["switchStyle","borderColor","backgroundColor","color"],
    emits:["switchChange"],
    // 内部属性
    setup(props,ctx) {
      const isOpen = ref(false)
      const left = ref('0px')

      const cssStyleBG = computed(() => {
        if (props.switchStyle === "mini") {
          return `position:relative;border-color:${props.borderColor};
          border-width:2px;border-style:solid;width:55px;height:30px;border-radius:30px;
          background-color:${isOpen.value ? props.backgroundColor:"white"};`
        } else {
          return `position:relative;border-color:${props.borderColor};
          border-width:2px;border-style:solid;width:55px;height:30px;border-radius:10px;
          background-color:${isOpen.value ? props.backgroundColor:"white"};`
        }
      })

      const cssStyleBtn = computed(() => {
        if (props.switchStyle === "mini") {
          return `position:absolute;width:30px;height:30px;left:${left.value};
          border-radius:50%;background-color:${props.color};`
        } else {
          return `position:absolute;width:30px;height:30px;left:${left.value};
          border-radius:8px;background-color:${props.color};`
        }
      })

      // 组件状态切换
      const click = () => {
        isOpen.value = !isOpen.value
        left.value = isOpen.value ? "25px" : "0px"
        ctx.emit('switchChange',isOpen.value)
      }
      return {isOpen,left,cssStyleBG,cssStyleBtn,click}
    },
    template:`
        <div :style="cssStyleBG" @click="click">
          <div :style="cssStyleBtn"></div>
        </div>
    `
  }
  const app = createApp({
    setup() {
      const state1 = ref("关")
      const state2 = ref("关")
      const change1 = (isOpen) => {
        state1.value = isOpen ? "开" : "关"
      }
      const change2 = (isOpen) => {
        state2.value = isOpen ? "开" : "关"
      }
      return {state1,state2,change1,change2}
    }
  })
  app.component("my-switch",switchComponent)
  app.mount("#app")
</script>
</body>
</html>